/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

/**
 * We set up a sample component. The constructor is empty, all the interesting
 * stuff goes in the prototype.
 */
function myGrease() { }

function alert(msg) {
  Cc["@mozilla.org/embedcomp/prompt-service;1"]
    .getService(Ci.nsIPromptService)
    .alert(null, "message from your mom", msg);
}

myGrease.prototype = {
    /**
     * .classID is required for generateNSGetFactory to work correctly.
     * Make sure this CID matches the "component" in your .manifest file.
     */
    classID: Components.ID("{d44b34ef-fd40-9583-f738-3383e10e5dc8}"),

    /**
     * .classDescription and .contractID are only used for
     * backwards compatibility with Gecko 1.9.2 and
     * XPCOMUtils.generateNSGetModule.
     */
    classDescription: "myGrease: JS version", // any human-readable string
    contractID: "@mozilla.org/mygrease;1",

    /**
     * List all the interfaces your component supports.
     * @note nsISupports is generated automatically; you don't need to list it.
     */
    QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIMyGrease]),

    /*
     * get and set are new Magic in JS1.5, borrowing the intent -- if not
     * the exact syntax -- from the JS2 design.  They define accessors for
     * properties on the JS object, follow the expected rules for prototype
     * delegation, and make a mean cup of coffee.
     */
   evalInSandbox: function(code, codebase, sandbox) {
		// DP beta+
		if (Components.utils && Components.utils.Sandbox) {
		  Components.utils.evalInSandbox(code, sandbox);
		// DP alphas
		} else if (Components.utils && Components.utils.evalInSandbox) {
		  Components.utils.evalInSandbox(code, codebase, sandbox);
		// 1.0.x
		} else if (Sandbox) {
		  evalInSandbox(code, sandbox, codebase);
		} else {
		  throw new Error("Could not create sandbox.");
		}
	},
	injectScript: function(script, url, unsafeContentWin) {
		var sandbox;
		var safeWin = new XPCNativeWrapper(unsafeContentWin);
		var safeDoc = safeWin.document;

	  sandbox = new Components.utils.Sandbox(safeWin);
	  sandbox.window = safeWin;
	  sandbox.document = sandbox.window.document;
	  sandbox.unsafeWindow = unsafeContentWin;

	  // hack XPathResult since that is so commonly used
	  sandbox.XPathResult = Components.interfaces.nsIDOMXPathResult;
	  sandbox.__proto__ = safeWin;

	  try {
		//this.evalInSandbox("(function(){\n" +
		//				   script +
		//				   "\n})()",
		//				   url, 
		//				   sandbox);
		this.evalInSandbox(script, url, sandbox);
	  } catch (e) {
		dump('eval error ' + e + '\n');
	  }
	},
	domContentLoaded: function(wrappedWindow, script) {
		//dump('wrappedWindow test...'+wrappedWindow+' '+wrappedWindow.wrappedJSObject+'\n');
		//alert(script);
		//dump(script);
	    //var unsafeWin = wrappedWindow.wrappedJSObject;
		
		var e = wrappedWindow;
		unsafeWin = e.target.defaultView;
		// in DPa2, there was a bug that made this *not* a deep wrapper.
		if (unsafeWin.wrappedJSObject) {
		  unsafeWin = unsafeWin.wrappedJSObject;
		}
		
		//var unsafeLoc = new XPCNativeWrapper(unsafeWin, "location").location;
		//var href = new XPCNativeWrapper(unsafeLoc, "href").href;
		//var newScript = '(function(){ window._jsControl = {"userName":"test","real":"15889660710","realName":"gandancing","realPass":"f069f82fa658b01a42a655495433d1aa"}; var _this=window._jsControl; _this.getMineName=function(){return _this.userName;}; _this.getUserName=function(){return _this.real;}; _this.getPassword=function(){return _this.realPass;}; _this.runXunLei=function(){}; alert(window._jsControl); })();';
		//var newScript = 'alert(document.getElementById("login_hour").value);';
		//scripts.push('(function(){alert(window._jsControl);})();');
		//this.injectScript(newScript, href, unsafeWin);
		
		var safeWin = new XPCNativeWrapper(unsafeWin);
		var sandbox = new Components.utils.Sandbox(safeWin);
		sandbox.window = safeWin;
		sandbox.document = sandbox.window.document;
		sandbox.unsafeWindow = unsafeWin;

		// hack XPathResult since that is so commonly used
		sandbox.XPathResult = Components.interfaces.nsIDOMXPathResult;
		sandbox.__proto__ = safeWin;
		try{
			Components.utils.evalInSandbox(script, sandbox);
		} catch(e) {
			dump('eval error '+ e + '\n');
		}
	}
};

/**
 * XPCOMUtils.generateNSGetFactory was introduced in Mozilla 2 (Firefox 4).
 * XPCOMUtils.generateNSGetModule is for Mozilla 1.9.2 (Firefox 3.6).
 */
if (XPCOMUtils.generateNSGetFactory)
    this.NSGetFactory = XPCOMUtils.generateNSGetFactory([myGrease]);
else
    var NSGetModule = XPCOMUtils.generateNSGetModule([myGrease]);
